<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="跟进人" prop="followUpPerson">
        <el-select v-model="queryParams.followUpPerson" placeholder="请选择跟进人" clearable filterable @change="handleFollowUpPersonChange">
          <el-option
            v-for="item in userOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="日期范围" prop="dateRange">
        <el-date-picker
          v-model="queryParams.dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="联系类型" prop="contactType">
        <el-select v-model="queryParams.contactType" placeholder="请选择联系类型" clearable>
          <el-option
            v-for="dict in dict.type.contact_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="联系结果" prop="contactResult">
        <el-select v-model="queryParams.contactResult" placeholder="请选择联系结果" clearable>
          <el-option
            v-for="dict in dict.type.contact_result"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card total-card">
          <div slot="header" class="clearfix card-header">
            <i class="el-icon-s-data stat-icon"></i>
            <span>总联系次数</span>
            <span v-if="queryParams.followUpPerson" class="follow-up-title">{{ getFollowUpPersonName() }}</span>
            <el-button type="text" icon="el-icon-refresh" class="refresh-btn" @click="refreshData" title="刷新数据"></el-button>
          </div>
          <div class="card-body">
            <count-to :startVal="0" :endVal="statistics.totalContacts" :duration="2000" class="card-number"/>
            <div class="card-footer">
              <span>累计联系客户次数</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card monthly-card">
          <div slot="header" class="clearfix card-header">
            <i class="el-icon-date stat-icon"></i>
            <span>本月联系次数</span>
            <span v-if="queryParams.followUpPerson" class="follow-up-title">{{ getFollowUpPersonName() }}</span>
          </div>
          <div class="card-body">
            <count-to :startVal="0" :endVal="statistics.monthlyContacts" :duration="2000" class="card-number"/>
            <div class="card-footer">
              <span>本月联系客户次数</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card customer-card">
          <div slot="header" class="clearfix card-header">
            <i class="el-icon-user stat-icon"></i>
            <span>负责客户数</span>
            <span v-if="queryParams.followUpPerson" class="follow-up-title">{{ getFollowUpPersonName() }}</span>
          </div>
          <div class="card-body">
            <count-to :startVal="0" :endVal="statistics.customerCount" :duration="2000" class="card-number"/>
            <div class="card-footer">
              <span>负责的不同客户数量</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card success-card">
          <div slot="header" class="clearfix card-header">
            <i class="el-icon-warning-outline stat-icon"></i>
            <span>未跟进客户数</span>
            <span v-if="queryParams.followUpPerson" class="follow-up-title">{{ getFollowUpPersonName() }}</span>
          </div>
          <div class="card-body">
            <count-to :startVal="0" :endVal="statistics.notFollowedCount || 0" :duration="2000" class="card-number"/>
            <div class="card-footer">
              <span>尚未联系的客户数量</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 联系记录列表 -->
    <el-card class="box-card table-card">
      <div slot="header" class="clearfix card-header">
        <i class="el-icon-document stat-icon"></i>
        <span>联系记录详情</span>
        <span v-if="queryParams.followUpPerson" class="follow-up-title">{{ getFollowUpPersonName() }}</span>
      </div>
      <el-table
        v-loading="loading"
        :data="contactList"
        style="width: 100%"
        stripe
        border
        class="stats-table"
      >
        <el-table-column label="客户名称" align="center" prop="customerName" />
        <el-table-column label="联系方式" align="center" prop="contactType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.contact_type" :value="scope.row.contactType"/>
          </template>
        </el-table-column>
        <el-table-column label="联系人" align="center" prop="contactPerson" />
        <el-table-column label="联系结果" align="center" prop="contactResult">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.contact_result" :value="scope.row.contactResult"/>
          </template>
        </el-table-column>
        <el-table-column label="联系时间" align="center" prop="contactTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.contactTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="联系内容" align="center" prop="contactContent" show-overflow-tooltip />
        <el-table-column label="跟进人" align="center" prop="createBy" />
      </el-table>
      
      <div class="pagination-container">
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="handlePaginationChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog :title="'跟进人详情 - ' + detailsTitle" :visible.sync="detailsDialogVisible" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="跟进人">{{ detailsData.followUpPerson }}</el-descriptions-item>
        <el-descriptions-item label="总联系次数">{{ detailsData.totalContacts }}</el-descriptions-item>
        <el-descriptions-item label="本月联系次数">{{ detailsData.monthlyContacts }}</el-descriptions-item>
        <el-descriptions-item label="已接通次数">{{ detailsData.successfulContacts }}</el-descriptions-item>
        <el-descriptions-item label="未接通次数">{{ detailsData.unsuccessfulContacts }}</el-descriptions-item>
        <el-descriptions-item label="负责客户数">{{ detailsData.customerCount }}</el-descriptions-item>
        <el-descriptions-item label="未跟进客户数">{{ detailsData.notFollowedCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="接通率" :span="2">
          <el-progress 
            :percentage="parseFloat((detailsData.successRate * 100).toFixed(1))" 
            :color="getSuccessRateColor(detailsData.successRate)"
            :stroke-width="20"
          ></el-progress>
        </el-descriptions-item>
      </el-descriptions>
      
      <div class="chart-container" style="margin-top: 20px;">
        <h3>联系方式分布</h3>
        <div class="chart-wrapper" style="height: 300px;">
          <v-chart :options="detailsTypeChartOptions" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getHandlerContactStats } from "@/api/system/customer";
import { listContactRecord } from "@/api/system/contactrecord";
import { listUser } from "@/api/system/user";
import CountTo from 'vue-count-to'

export default {
  name: "FollowUpStats",
  components: {
    CountTo
  },
  dicts: ['contact_type', 'contact_result'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 联系记录表格数据
      contactList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        followUpPerson: null,
        contactType: null,
        contactResult: null,
        dateRange: []
      },
      // 表单提交参数，这将实际发送给后端API
      formParams: {
        pageNum: 1,
        pageSize: 20,
        createBy: null,
        contactType: null,
        contactResult: null,
        beginTime: null,
        endTime: null
      },
      // 统计数据
      statistics: {
        totalContacts: 0,
        monthlyContacts: 0,
        customerCount: 0,
        successRate: 0,
        notFollowedCount: 0
      },
      // 用户下拉选项
      userOptions: [],
      // 是否使用模拟数据（后端API未完成时）- 改为false确保使用真实数据
      useMockData: false,
      // 模拟数据提示
      mockTip: false,
      // 跟进人详情对话框
      detailsDialogVisible: false,
      detailsTitle: '',
      detailsData: {
        followUpPerson: '',
        totalContacts: 0,
        monthlyContacts: 0,
        successfulContacts: 0,
        unsuccessfulContacts: 0,
        customerCount: 0,
        successRate: 0,
        contactTypes: []
      },
      // 前端数据缓存
      dataCache: {},
      // 缓存过期时间（设为0秒，实际上禁用了缓存）
      cacheExpireTime: 0,
      // 趋势图配置
      trendChartOptions: {
        title: {
          text: '跟进人联系趋势',
          left: 'center',
          textStyle: {
            fontSize: 16
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          },
          formatter: function(params) {
            const value = params[0].value || 0;
            return `${params[0].name}<br/>联系次数: ${value} 次`;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          top: '15%',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: { title: '保存为图片' },
            dataView: { title: '数据视图', lang: ['数据视图', '关闭', '刷新'] },
            magicType: {
              type: ['line', 'bar'],
              title: {
                line: '切换为折线图',
                bar: '切换为柱状图'
              }
            }
          },
          right: '20px'
        },
        dataZoom: [{
          type: 'slider',
          show: true,
          start: 0,
          end: 100,
          bottom: 10,
          height: 30,
          borderColor: 'transparent',
          backgroundColor: '#f5f7fa',
          fillerColor: 'rgba(64, 158, 255, 0.2)',
          handleStyle: {
            color: '#409EFF',
            borderColor: '#409EFF'
          }
        }, {
          type: 'inside',
          start: 0,
          end: 100
        }],
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: [],
          axisLine: {
            lineStyle: {
              color: '#909399'
            }
          },
          axisLabel: {
            color: '#606266',
            fontSize: 12,
            rotate: 30
          }
        },
        yAxis: {
          type: 'value',
          name: '联系次数',
          nameTextStyle: {
            color: '#606266',
            fontSize: 12,
            padding: [0, 0, 0, 40]
          },
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#E4E7ED'
            }
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#909399'
            }
          },
          axisLabel: {
            color: '#606266',
            fontSize: 12
          }
        },
        series: [
          {
            name: '联系次数',
            type: 'line',
            stack: '总量',
            data: [],
            smooth: true,
            symbol: 'emptyCircle',
            symbolSize: 8,
            showSymbol: true,
            lineStyle: {
              width: 4,
              color: '#409EFF'
            },
            itemStyle: {
              color: '#409EFF',
              borderWidth: 2
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0,
                  color: 'rgba(64,158,255,0.7)'
                }, {
                  offset: 1,
                  color: 'rgba(64,158,255,0.1)'
                }]
              }
            }
          }
        ]
      },
      // 联系类型分布图配置
      typeChartOptions: {
        title: {
          text: '联系类型分布',
          left: 'center',
          textStyle: {
            fontSize: 16
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          top: 'middle',
          data: [],
          textStyle: {
            color: '#606266'
          }
        },
        toolbox: {
          feature: {
            saveAsImage: { title: '保存为图片' },
            dataView: { title: '数据视图', lang: ['数据视图', '关闭', '刷新'] }
          },
          right: '20px'
        },
        color: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#B656D6'],
        series: [
          {
            name: '联系类型',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['60%', '55%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}: {d}%',
              fontSize: 14
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 16,
                fontWeight: 'bold'
              },
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            labelLine: {
              show: true,
              length: 15,
              length2: 10
            },
            data: []
          }
        ]
      },
      // 详情页联系类型分布图
      detailsTypeChartOptions: {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: []
        },
        series: [
          {
            name: '联系类型',
            type: 'pie',
            radius: '55%',
            center: ['50%', '50%'],
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getUsers();
    this.getResponsibleCustomerStats();

    // 如果使用模拟数据，显示提示
    if(this.useMockData && this.mockTip) {
      this.$notify({
        title: '提示',
        message: '当前使用模拟数据模式，接口404错误已被屏蔽',
        type: 'warning',
        duration: 5000
      });
      this.mockTip = false;
    }
  },
  methods: {
    /** 获取用户列表 */
    getUsers() {
      // 先检查缓存
      if (this.getCachedData('users')) {
        this.userOptions = this.getCachedData('users');
        console.log('使用缓存的用户列表数据');
        return;
      }

      const startTime = Date.now();
      listUser({
        pageSize: 200
      }).then(response => {
        this.userOptions = response.rows.map(user => ({
          value: user.userName,
          label: user.nickName
        }));
        // 缓存用户列表数据 - 较长时间
        this.setCachedData('users', this.userOptions, 30 * 60 * 1000); // 30分钟
        console.log('获取用户列表成功，耗时:', Date.now() - startTime, 'ms');
      }).catch(() => {
        console.error('获取用户列表失败');
        this.$message.error('获取用户列表失败');
      });
    },
    
    /** 查询联系记录列表 */
    getList() {
      this.loading = true;
      
      // 打印调试跟进人信息
      console.log('当前跟进人设置为:', this.queryParams.followUpPerson);
      
      if (this.useMockData) {
        // 使用模拟数据
        this.$nextTick(() => {
          let records = this.getMockContactRecords();
          
          // 如果选择了跟进人，则筛选模拟数据
          if (this.queryParams.followUpPerson) {
            records = records.filter(record => record.createBy === this.queryParams.followUpPerson);
            console.log('筛选后的模拟记录:', records.length);
          }
          
          this.contactList = records;
          this.total = records.length;
          this.loading = false;
        });
        return;
      }
      
      // 根据查询参数更新表单提交参数
      this.updateFormParams();
      
      // 添加时间戳避免浏览器缓存
      this.formParams._t = Date.now();
      
      console.log('查询联系记录列表，最终参数:', JSON.stringify(this.formParams));
      
      // 性能监控开始
      const startTime = Date.now();
      
      // 使用contactrecord接口来获取联系记录列表
      listContactRecord(this.formParams).then(response => {
        const endTime = Date.now();
        console.log('获取联系记录列表响应，耗时:', endTime - startTime, 'ms');
        
        if (response.code === 200) {
          // 检查返回的数据是否为空数组
          if (!response.rows || response.rows.length === 0) {
            console.log('警告: 后端返回空记录，可能参数不匹配');
            this.$message.warning('未找到符合条件的记录，请检查筛选条件');
          }
          
          const records = Array.isArray(response.rows) ? response.rows.map(row => ({
            ...row,
            contactType: row.contactType || null,
            contactResult: row.contactResult || null
          })) : [];
          
          this.contactList = records;
          this.total = response.total || 0;
          
          // 调试跟进人筛选结果
          this.validateResults();
        } else {
          this.$message.error(response.msg || '获取联系记录列表失败');
          this.contactList = [];
          this.total = 0;
        }
        this.loading = false;
      }).catch(error => {
        console.error('获取联系记录列表失败:', error);
        if (this.useMockData) {
          // 如果API接口失败，使用模拟数据
          let records = this.getMockContactRecords();
          if (this.queryParams.followUpPerson) {
            records = records.filter(record => record.createBy === this.queryParams.followUpPerson);
          }
          this.contactList = records;
          this.total = records.length;
        } else {
          this.contactList = [];
          this.total = 0;
          this.$message.error('获取联系记录列表失败');
        }
        this.loading = false;
      });
    },
    
    /** 验证返回结果是否符合跟进人筛选条件 */
    validateResults() {
      // 如果指定了跟进人，验证返回数据是否符合条件
      if (this.queryParams.followUpPerson && this.contactList.length > 0) {
        // 验证返回的数据是否符合跟进人筛选条件
        const correctRecords = this.contactList.filter(item => 
          item.createBy === this.queryParams.followUpPerson);
        
        console.log('实际匹配的跟进人记录:', correctRecords.length, '总记录:', this.contactList.length);
        
        if (correctRecords.length !== this.contactList.length && correctRecords.length > 0) {
          // 如果后端返回的数据不完全匹配但有部分匹配，手动进行前端筛选
          console.warn('警告: 后端返回的数据与请求的跟进人不完全匹配，执行前端筛选');
          this.contactList = correctRecords;
          this.total = correctRecords.length;
        } else if (correctRecords.length === 0 && this.contactList.length > 0) {
          console.warn('警告: 后端返回的数据可能使用了不同的字段名，无法在前端确认匹配');
        }
      }
    },
    
    /** 更新表单提交参数 */
    updateFormParams() {
      // 复制基本查询参数
      this.formParams.pageNum = this.queryParams.pageNum;
      this.formParams.pageSize = this.queryParams.pageSize;
      this.formParams.contactType = this.queryParams.contactType;
      this.formParams.contactResult = this.queryParams.contactResult;
      
      // 记录当前页码和每页条数，用于调试
      console.log('当前页码:', this.formParams.pageNum, '每页条数:', this.formParams.pageSize);
      
      // 跟进人参数处理 - 直接映射为createBy
      this.formParams.createBy = this.queryParams.followUpPerson;
      
      // 处理日期范围
      if (this.queryParams.dateRange && this.queryParams.dateRange.length === 2) {
        this.formParams.beginTime = this.queryParams.dateRange[0];
        this.formParams.endTime = this.queryParams.dateRange[1];
      } else {
        this.formParams.beginTime = null;
        this.formParams.endTime = null;
      }
      
      // 记录最新参数用于调试
      if (this.formParams.createBy) {
        console.log('发送跟进人筛选参数:', this.formParams.createBy);
      }
    },
    
    /** 获取负责客户统计数据 */
    getResponsibleCustomerStats() {
      if (this.useMockData) {
        // 使用模拟数据
        this.$nextTick(() => {
          this.statistics = this.getMockStatistics();
        });
        return;
      }
      
      // 构建查询参数
      const params = {};
      
      // 确保后端需要的参数正确传递
      if (this.queryParams.followUpPerson) {
        // 使用handlerName参数传递跟进人信息
        params.handlerName = this.queryParams.followUpPerson;
      }
      
      // 可能的日期参数传递
      if (this.queryParams.dateRange && this.queryParams.dateRange.length === 2) {
        params.beginTime = this.queryParams.dateRange[0];
        params.endTime = this.queryParams.dateRange[1];
      }
      
      // 添加随机参数避免浏览器缓存
      params._t = Date.now();
      
      const startTime = Date.now();
      console.log('获取负责客户统计数据，参数:', params);
      
      // 直接使用getHandlerContactStats接口获取数据
      getHandlerContactStats(params).then(response => {
        console.log('获取负责客户统计数据响应，耗时:', Date.now() - startTime, 'ms');
        
        if (response.code === 200) {
          // 创建处理数据的方法
          const processedStats = this.processStatisticsData(response.data);
          
          // 更新统计信息
          this.statistics = processedStats;
          
          // 打印最终结果，用于调试
          console.log('最终统计数据:', this.statistics);
        } else {
          console.error('获取负责客户统计数据返回错误:', response);
          if (this.useMockData) {
            this.statistics = this.getMockStatistics();
          } else {
            this.$message.error(response.msg || '获取负责客户统计数据失败');
          }
        }
      }).catch(error => {
        console.error('获取负责客户统计数据失败:', error);
        if (this.useMockData) {
          // 如果API接口失败，使用模拟数据
          this.statistics = this.getMockStatistics();
        } else {
          this.$message.error('获取负责客户统计数据失败');
        }
      });
    },
    
    /**
     * 处理统计数据 - 从不同格式的响应中提取数据
     */
    processStatisticsData(data) {
      // 默认结果对象
      const result = {
        totalContacts: 0,
        monthlyContacts: 0,
        customerCount: 0,
        successRate: 0,
        notFollowedCount: 0
      };
      
      // 响应格式1: 数组格式
      if (Array.isArray(data)) {
        const statsList = data;
        
        // 如果指定了特定的跟进人，则筛选对应数据
        let targetStats = null;
        if (this.queryParams.followUpPerson) {
          targetStats = statsList.find(item => 
            item.handlerName === this.queryParams.followUpPerson);
        } else if (statsList.length > 0) {
          // 否则汇总所有数据
          targetStats = statsList.reduce((acc, current) => {
            acc.totalContacts = (acc.totalContacts || 0) + (current.totalContacts || 0);
            acc.monthlyContacts = (acc.monthlyContacts || 0) + (current.monthlyContacts || 0);
            acc.customerCount = (acc.customerCount || 0) + (current.customerCount || 0);
            acc.notFollowedCount = (acc.notFollowedCount || 0) + (current.notFollowedCount || 0);
            return acc;
          }, {});
        }
        
        if (targetStats) {
          // 更新统计信息
          result.totalContacts = targetStats.totalContacts || 0;
          result.monthlyContacts = targetStats.monthlyContacts || 0;
          result.customerCount = targetStats.customerCount || 0;
          result.successRate = targetStats.successRate || 0;
          result.notFollowedCount = targetStats.notFollowedCount || 0;
        }
      } 
      // 响应格式2: 包含statsList的对象
      else if (data && data.statsList && data.statsList.length > 0) {
        const statsList = data.statsList;
        
        // 如果指定了特定的跟进人，则筛选出对应数据
        let targetStats = null;
        if (this.queryParams.followUpPerson) {
          targetStats = statsList.find(item => item.handlerName === this.queryParams.followUpPerson);
        } else if (statsList.length > 0) {
          // 否则汇总所有数据
          targetStats = statsList.reduce((acc, current) => {
            acc.totalContacts = (acc.totalContacts || 0) + (current.totalContacts || 0);
            acc.monthlyContacts = (acc.monthlyContacts || 0) + (current.monthlyContacts || 0);
            acc.customerCount = (acc.customerCount || 0) + (current.customerCount || 0);
            acc.notFollowedCount = (acc.notFollowedCount || 0) + (current.notFollowedCount || 0);
            return acc;
          }, {});
        }
        
        if (targetStats) {
          // 更新统计信息
          result.totalContacts = targetStats.totalContacts || 0;
          result.monthlyContacts = targetStats.monthlyContacts || 0;
          result.customerCount = targetStats.customerCount || 0;
          result.successRate = targetStats.successRate || 0;
          result.notFollowedCount = targetStats.notFollowedCount || 0;
        }
      } 
      // 响应格式3: 直接返回的统计数据
      else if (data) {
        result.totalContacts = data.totalContacts || data.totalCount || 0;
        result.monthlyContacts = data.monthlyContacts || data.monthCount || 0;
        result.customerCount = data.customerCount || 0;
        result.successRate = data.successRate || 0;
        result.notFollowedCount = data.notFollowedCount || data.notContactedCount || data.uncontactedCount || 0;
      }
      
      return result;
    },
    
    /**
     * 获取缓存数据
     */
    getCachedData(key) {
      const cachedItem = this.dataCache[key];
      if (!cachedItem) return null;
      
      // 检查缓存是否过期
      if (Date.now() - cachedItem.timestamp > this.cacheExpireTime) {
        // 缓存已过期，删除
        delete this.dataCache[key];
        return null;
      }
      
      return cachedItem.data;
    },
    
    /**
     * 设置缓存数据
     */
    setCachedData(key, data, expireTime = null) {
      this.dataCache[key] = {
        data: data,
        timestamp: Date.now()
      };
      
      // 如果提供了自定义过期时间
      if (expireTime) {
        setTimeout(() => {
          delete this.dataCache[key];
        }, expireTime);
      }
    },
    
    /** 生成模拟联系记录数据 */
    getMockContactRecords() {
      const contactTypes = ['1', '2', '3', '4']; // 假设这些是联系类型的value值
      const contactResults = ['0', '1']; // 假设这些是联系结果的value值
      const customers = ['武汉鸿合科技有限公司', '长沙思创科技', '深圳大洋科技', '北京联想集团', '上海华为技术'];
      const contacts = ['张三', '李四', '王五', '赵六', '钱七'];
      const users = ['admin', 'zhangsan', 'lisi', 'wangwu', 'zhaoliu'];
      
      const records = [];
      
      for (let i = 0; i < 20; i++) {
        const date = new Date();
        date.setDate(date.getDate() - Math.floor(Math.random() * 30));
        
        records.push({
          id: i + 1,
          customerName: customers[Math.floor(Math.random() * customers.length)],
          contactType: contactTypes[Math.floor(Math.random() * contactTypes.length)],
          contactPerson: contacts[Math.floor(Math.random() * contacts.length)],
          contactResult: contactResults[Math.floor(Math.random() * contactResults.length)],
          contactTime: date.getTime(),
          contactContent: '这是一条模拟的联系记录内容，描述了与客户的沟通过程。',
          createBy: users[Math.floor(Math.random() * users.length)]
        });
      }
      
      return records;
    },
    
    /** 生成模拟统计数据 */
    getMockStatistics() {
      // 基础模拟数据
      const baseStats = {
        totalContacts: 328,
        monthlyContacts: 86,
        customerCount: 42,
        successRate: 0.72,
        notFollowedCount: 15
      };
      
      // 如果选择了特定跟进人，则生成针对该跟进人的模拟数据
      if (this.queryParams.followUpPerson) {
        // 获取用户名的第一个字符作为随机数种子
        const seed = this.queryParams.followUpPerson.charCodeAt(0) || 0;
        
        // 根据跟进人生成不同的模拟数据
        return {
          totalContacts: 50 + (seed % 10) * 20,
          monthlyContacts: 10 + (seed % 7) * 5,
          customerCount: 15 + (seed % 5) * 3,
          notFollowedCount: 3 + (seed % 4) * 2,
          successRate: 0.6 + (seed % 3) * 0.1
        };
      }
      
      return baseStats;
    },
    
    /** 搜索按钮操作 */
    handleQuery() {
      console.log('执行查询，参数:', JSON.stringify(this.queryParams));
      
      // 性能监控
      const startTime = Date.now();
      
      // 重置页码
      this.queryParams.pageNum = 1;
      
      // 确保每页条数保持一致
      this.formParams.pageSize = this.queryParams.pageSize;
      
      // 查询前先清空列表数据，避免显示旧数据
      this.contactList = [];
      this.total = 0;
      
      // 清空统计数据
      this.statistics = {
        totalContacts: 0,
        monthlyContacts: 0,
        customerCount: 0,
        successRate: 0,
        notFollowedCount: 0
      };
      
      // 查询数据
      const getListPromise = this.getList();
      const getStatsPromise = this.getResponsibleCustomerStats();
      
      // 使用Promise.all同时发起查询并等待所有完成
      Promise.all([getListPromise, getStatsPromise].filter(Boolean))
        .then(() => {
          console.log('查询操作完成，总耗时:', Date.now() - startTime, 'ms');
        })
        .catch(err => {
          console.error('查询过程中发生错误:', err);
        });
    },
    
    /** 重置按钮操作 */
    resetQuery() {
      // 记录当前状态，用于判断是否需要重新加载数据
      const prevFollowUpPerson = this.queryParams.followUpPerson;
      const prevDateRange = this.queryParams.dateRange;
      
      // 重置表单
      this.resetForm("queryForm");
      
      // 如果筛选条件有变化，则重新查询
      if (prevFollowUpPerson !== this.queryParams.followUpPerson || 
          JSON.stringify(prevDateRange) !== JSON.stringify(this.queryParams.dateRange)) {
        this.handleQuery();
      } else {
        console.log('筛选条件未变化，无需重新查询');
      }
    },
    
    /** 获取接通率颜色 */
    getSuccessRateColor(rate) {
      if (rate >= 0.8) {
        return '#67C23A';  // 绿色 - 优秀
      } else if (rate >= 0.6) {
        return '#E6A23C';  // 黄色 - 良好
      } else {
        return '#F56C6C';  // 红色 - 需改进
      }
    },
    
    /** 获取跟进人显示名称 */
    getFollowUpPersonName() {
      if (!this.queryParams.followUpPerson) return '';
      
      const found = this.userOptions.find(user => user.value === this.queryParams.followUpPerson);
      return found ? found.label : this.queryParams.followUpPerson;
    },
    
    /** 处理跟进人变化 */
    handleFollowUpPersonChange(value) {
      console.log('跟进人选择变化:', value);
      
      // 明确记录选择的跟进人值
      if (value) {
        console.log('选择了跟进人:', value);
        
        // 弹出提示，显示正在筛选
        this.$message.info(`正在筛选跟进人: ${this.getFollowUpPersonName() || value}`);
      } else {
        console.log('清空了跟进人筛选');
      }
      
      // 执行查询
      this.handleQuery();
    },
    
    /** 刷新所有数据 */
    refreshData() {
      this.$message({
        message: '正在刷新数据...',
        type: 'info',
        duration: 1000
      });
      
      // 清空当前数据
      this.statistics = {
        totalContacts: 0,
        monthlyContacts: 0,
        customerCount: 0,
        successRate: 0,
        notFollowedCount: 0
      };
      
      this.contactList = [];
      this.total = 0;
      
      // 强制从服务器获取新数据
      this.getList();
      this.getResponsibleCustomerStats();
    },
    
    /** 处理分页变化 */
    handlePaginationChange() {
      // 确保formParams与queryParams保持同步
      this.formParams.pageNum = this.queryParams.pageNum;
      this.formParams.pageSize = this.queryParams.pageSize;
      
      console.log('分页变化，当前页码:', this.formParams.pageNum, '每页条数:', this.formParams.pageSize);
      
      const startTime = Date.now();
      this.getList().then(() => {
        console.log('分页查询完成，耗时:', Date.now() - startTime, 'ms');
      });
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.statistics-cards {
  margin-bottom: 20px;
}

.card-body {
  text-align: center;
  padding: 20px 0;
}

.card-number {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  display: block;
  margin-bottom: 10px;
}

.card-footer {
  margin-top: 15px;
  color: #909399;
  font-size: 14px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-card {
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

.total-card .card-header {
  background: linear-gradient(120deg, #e0f7fa, #b2ebf2);
  color: #00838f;
}

.monthly-card .card-header {
  background: linear-gradient(120deg, #f1f8e9, #c5e1a5);
  color: #558b2f;
}

.customer-card .card-header {
  background: linear-gradient(120deg, #e8eaf6, #c5cae9);
  color: #3949ab;
}

.success-card .card-header {
  background: linear-gradient(120deg, #fff3e0, #ffcc80);
  color: #e65100;
}

.success-card .card-number {
  color: #f57c00;
}

.card-header {
  display: flex;
  align-items: center;
  padding: 15px !important;
  border-bottom: 1px solid #ebeef5;
}

.stat-icon {
  font-size: 20px;
  margin-right: 10px;
}

.table-card {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.stats-table {
  margin-top: 10px;
  width: 100%;
  border-radius: 5px;
  overflow: hidden;
}

.highlight-value {
  font-weight: bold;
  color: #409EFF;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.follow-up-title {
  font-size: 14px;
  color: #409EFF;
  margin-left: 10px;
  font-weight: bold;
  background-color: rgba(64, 158, 255, 0.1);
  padding: 2px 8px;
  border-radius: 4px;
}

.refresh-btn {
  float: right;
  padding: 3px 0;
  color: #909399;
  transition: all 0.3s;
}

.refresh-btn:hover {
  color: #409EFF;
  transform: rotate(180deg);
}
</style> 